package com.andkrup.comm {
	import flash.display.BitmapData;	
	import flash.net.URLVariables;	
	
	import com.adobe.serialization.json.JSON;	
	import com.adobe.net.URI;	
	
	/**
	 * @author Andkrup
	 * 
	 * When loading external data, you typically agree with the backend developer
	 * about a dataformat and then transfer alot of text over http.
	 * 
	 * This little helper class looks at the file-suffix of the uri and tries to
	 * cast the textual or binary data into a usable type.
	 * 
	 * When asking this class to load a swf resource, it is implied that the swf
	 * resource primarily contains run-time assets such as class definitions and
	 * interface implementors.
	 * 
	 */
	public class ResourcePreParser implements IResourcePreParser {
		public static const SWF_SUFFIX:String = ".swf";
		public static const XML_SUFFIX:String = ".xml";
		public static const JSON_SUFFIX:String = ".json";
		public static const TEXT_SUFFIX:String = ".txt";
		public static const PNG_SUFFIX:String = ".png";
		public static const JPG_SUFFIX:String = ".jpg";
		public static const GIF_SUFFIX:String = ".gif";
		public static const PHP_SUFFIX:String = ".php";
		public static const ASP_SUFFIX:String = ".asp";
		public static const DOTNET_SUFFIX:String = ".aspx";
		public static const REWRITE_SUFFIX:String = "unknown";
		
		public function castToType(data:String, uri:URI = null):*{
			var filename:String = uri.getFilename();
			var suffix:String = filename.substring(filename.lastIndexOf("."));
			switch(suffix.toLowerCase()){
				case XML_SUFFIX:
					return new XML(data);
				case JSON_SUFFIX:
					return JSON.decode(data);
				case TEXT_SUFFIX:
					var urlv:URLVariables = new URLVariables();
					urlv.decode(data);
					return urlv;
				case PNG_SUFFIX:
				case JPG_SUFFIX:
				case GIF_SUFFIX:
					return BitmapData(data);
				default:
					return data;
			}
		}
	}
}
